import { Message, Loading } from 'element-ui';

const ui = {
    setPageTitle(title) {
        const titleElem = document.getElementsByTagName('title')[0];

        if(titleElem) {
            titleElem.innerText = title;
        }

        document.title = title;
    },
    showTips(message, type = 'info', duration = 2500) {
        return new Message({
            duration,
            message,
            type
        });
    },
    showLoader(message, lock = true) {
        const loader = ui.loader || Loading.service({
            customClass: 'ui-loader ui-loader-global',
            text: message,
            lock: lock
        });

        Object.assign(loader, {
            visible: true,
            text: message,
            lock: lock
        });

        ui.loader = loader;

        return loader;
    },
    hideLoader() {
        if(ui.loader) {
            ui.loader.close();
        }
    },
    showError(err) {
        console.error('UI.showError:', err);

        if(typeof err === 'string') {
            err = new Error(err);
        }

        if(!err || !(err instanceof Error)) {
            err = new Error('showError not accept: ' + err);
        }

        let message = err.message;
        if(err.status) {
            message = `[${err.status}] ${message}`;
        }

        return ui.showTips(message, 'error', 3000);
    },

    // Vue plugin
    install(Vue) {
        const fns = [
            'setPageTitle',
            'showTips',
            'showLoader', 'hideLoader',
            'showError'
        ];

        fns.forEach(name => {
            Vue.prototype['$' + name] = function(...args) {
                return ui[name](...args);
            };
        });
    }
};

export default ui;
